const { default: axios } = require("axios");
const WXBizDataCrypt = require("../middleware/WXBizDataCrypt");
// const { createwxUser } = require("../service/wx.user.server")
const { createwxUser } = require("../service/wx_users.server")
const jwt = require('jwt-simple');
const SECRET = 'zhuoran'; // 自定义
class WxLogin {

    async wxyanzhen(ctx, next) {
        const { code, iv, encryptedData, userData } = ctx.request.body;
        var userDatas = {}
        const appid = "wx585ec52cf4979259";
        const secret = "0b4ba6d5a86fd13d8a48e5916072c11c";
        if (code) {
            try {
                const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
                    params: {
                        appid: appid,
                        secret: secret,
                        js_code: code,
                        grant_type: 'authorization_code'
                    }
                });
                const sessionKey = response.data.session_key;
                const openId = response.data.openid;
                const pc = new WXBizDataCrypt(appid, sessionKey);
                const data = pc.decryptData(encryptedData, iv);
                // console.log('解密后 data: ', data);
                const openIdRes = data.openId;
                console.log(openIdRes, "openId")
                userDatas = { ...userData._value, openId }
                console.log(userDatas, "添加后的对象")
                // 生成 token
                const token = jwt.encode(openIdRes, SECRET);
                // console.log(openIdRes);
                // 返回结果
                ctx.body = {
                    code: 200,
                    token: token,
                    msg: "登录成功"
                };
                //插入数据库
                try {
                    const res = await createwxUser(userDatas)
                    //     返回结果
                    ctx.body = {
                        code: 0,
                        message: "用户注册成功",
                        result: {},
                        token: token,
                        msg: "登录成功"
                    }
                } catch (err) {
                    ctx.app.emit('err', err, err)
                }
            } catch (error) {
                console.error('请求失败: ', error);
                ctx.body = {
                    code: 500,
                    message: '请求失败',
                    error: error.message
                };
            }
        } else {
            ctx.body = {
                code: 400,
                message: '缺少参数 code'
            };
        }
    }
}

module.exports = new WxLogin();